package com.rudolfheszele.smsselector.controller;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class SmsSelectorSmsReaderService extends Service
{
	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}
	
	@Override
	public void onCreate()
	{
		mSmsReaderController = null;
		mSmsReaderThread = null;
		mMainController = (SmsSelectorMainController)ControllerFactoryFactory.getControllerFactory().getController();
	}
	
	@Override
	public void onStart(Intent intent, int startId)
	{
		// If the thread is already started, there is nothing to do...
		// Can not throw an exception, because the base class' onStart() method throws nothing...
		//if(mSmsReaderThread != null)
		//	return;
		mMainController.registerSmsReaderService(this);
		// Start the thread
		mSmsReaderThread = new SmsSelectorSmsReaderThread(mSmsReaderController);
		mSmsReaderThread.start();
	}
	
	@Override
	public void onDestroy()
	{
		if(mSmsReaderThread.isAlive())
		{
			mSmsReaderThread.stopSmsReading();
		}
		mSmsReaderThread = null;
		mMainController = null;
	}
	
	public void addController(SmsReaderController controller)
	{
		mSmsReaderController = controller;
	}
	
	void pauseSmsReading()
	{
		if(mSmsReaderThread.isAlive() == true && mSmsReaderThread.isPaused() == false)
		{
			mSmsReaderThread.pauseSmsReading();
		}
	}
	
	void resumeSmsReading()
	{
		if(mSmsReaderThread.isAlive() == true && mSmsReaderThread.isPaused() == true)
		{
			mSmsReaderThread.resumeSmsReading();
		}
	}
	
	void cancelSmsReading()
	{
		if(mSmsReaderThread.isAlive())
		{
			mSmsReaderThread.stopSmsReading();
		}
	}

	private SmsReaderController mSmsReaderController;
	private SmsSelectorSmsReaderThread mSmsReaderThread;
	private SmsSelectorMainController mMainController;
}
